<?php
namespace app\wx\controller;

use think\Controller;

class Login extends Controller
{
    function index()
    {
        controller('Index')->_tpl();
        return $this->fetch('templates/wx/login.html');
    }

    public function login_redirect_uri()
    {
        $code=input('get.auth_code');
        $res=model('Qywx')->get_login_info($code);
        $data=json_decode($res,true);
        session('qywx_user',$data);
        $corpid=$data['corp_info']['corpid'];
        $com=db('company')->where('corpid',$corpid)->find();
        if($com['id']=='')
        {
            jump('/wx/reg/reg_member.html');
        }
        if($com['is_use']=='0')
        {
            jump('/wx/reg/reg_member.html');
        }
        if($com['is_start']==0)
        {
            jump('/wx/reg/company_start.html');
        }
        $db=db('company_db')->where('corpid',$corpid)->find();
        if($db['id']=='')
        {
            jump('/wx/reg/company_start.html');
        }
        session('cdb',$db);
        jump('/wxadmin');
    }

    public function set_login()
    {
        $code=input('get.auth_code');
        $corpid=input('get.corpid');
        $appstr=input('get.app');
        $res=model('Qywx')->get_login_info($code);
        $data=json_decode($res,true);
        session('qywx_user',$data);
        $corpid=$data['corp_info']['corpid'];
        //判断企业是否授权使用中
        $com=db('company')->where(['corpid'=>$corpid,'is_use'=>1])->find();
        if($com['id']=='')
        {
            jump('/wx/reg/reg_member.htmlapp=?'.$appstr);
        }
        //判断企业应用是否授权使用中
        $app=db('company_app')->where(['app'=>$appstr,'corpid'=>$corpid,'is_use'=>1])->find();
        if($app['id']=='')
        {
            jump('/wx/reg/add_app.html?app='.$appstr);
        }
        //判断企业数据是否初始化
        if($com['is_start']==0)
        {
            jump('/wx/reg/company_start.html?app='.$appstr);
        }
        //判断企业数据库是否初始化
        $db=db('company_db')->where('corpid',$corpid)->find();
        if($db['id']=='')
        {
            jump('/wx/reg/company_start.html?app='.$appstr);
        }
        session('cdb',$db);
        jump('/wxadmin?app='.$appstr);
    }

    function test_login()
    {
        $db=db('company_db')->where('corpid','wwd2ce7d0a0568e88a')->find();
        session('cdb',$db);
        $str='{"usertype":1,"user_info":{"userid":"lzh","name":"廖振皓","avatar":"http:\/\/p.qlogo.cn\/bizmail\/o5Dw7cUOdyibS1WUStwpcHzB4yvf7A1Jt44FB2F7I62t8KOcmXCz8NQ\/0"},"corp_info":{"corpid":"wwd2ce7d0a0568e88a"},"agent":[{"agentid":1000247,"auth_type":1},{"agentid":1000248,"auth_type":1}],"auth_info":{"department":[{"id":1,"writable":true}]}}';
        $arr=json_decode($str,true);
        session('qywx_user',$arr);
        dump($arr);
        dump(session('cdb'));
    }

    function login_out()
    {
        session('qywx_user',null);
        session('cdb',null);
        session('nav',null);
        jump('/wx/login');
    }

}